<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:include="include :: header">
</head>
<body class="hold-transition skin-blue sidebar-mini">
<!--添加-->
<div class="modal fade" id="modal-create">
    <div class="modal-dialog" style="width:100%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">添加预购计划</h4>
            </div>
            <div class="modal-body">
                <section class="content" style="padding: 5px!important;">
                    <div class="row" style="margin-bottom: 24px">
                        <button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>
                        <a id="btn-create-report-plan" shiro:hasPermission="buy:preorderplan:add"
                           href="javascript:void(0);"
                           class="btn btn-info pull-right" style="margin-right: 10px">
                            <span class="Bold">确定</span>
                        </a>
                        <a shiro:hasPermission="buy:preorderplan:add" href="javascript:void(0);"
                           class="btn btn-success pull-right" style="margin-right: 10px"
                           onclick="js.modal.open('modal-import-plan')">
                            <span class="Bold">导入</span>
                        </a>
                    </div>
                    <div class="row">
                        <form id="createPreOrderPlanForm" class="form-horizontal">
                            <div class="col-xs-12"
                                 style="max-width: 100%;max-height: 80vh;overflow: auto;padding: 0!important;">
                                <table id="table_import" class="t1 t3">
                                    <thead>
                                    <!--                                    <tr>-->
                                    <!--                                        <td colspan="12">-->
                                    <!--                                            <img th:src="@{/img/logo.png}" width="64px" height="40px"-->
                                    <!--                                                 style="margin-top: -30px">-->
                                    <!--                                            <div style="display: inline-block;margin-top: 5px;margin-left: 20px">-->
                                    <!--                                                <span style="letter-spacing: 24px;display: block;line-height: 20px">&nbsp;辽宁忠旺机械设备制造有限公司</span>-->
                                    <!--                                                <span style="display: block;font-size: 12px;line-height: 20px">Liaoning Zhongwang Machinery Equipment Manufacturing Co., Ltd</span>-->
                                    <!--                                            </div>-->
                                    <!--                                        </td>-->
                                    <!--                                        <td style="width: 8%"></td>-->
                                    <!--                                    </tr>-->
                                    <tr>
                                        <td colspan="12" style="font-size: 16px;letter-spacing: 4px;">
                                            预购计划单
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" style="width: 8%">主题</td>
                                        <td colspan="7" style="width: 11%;font-size: 14px;">
                                            <input type="text" class="form-control" name="name"
                                                   placeholder="请输入预购主题"/>
                                        </td>
                                        <td style="width: 8%">预购编号</td>
                                        <td colspan="2" style="width: 21%">
                                            <input style="background: #FFFFFF" type="text" class="form-control"
                                                   name="code" readonly="readonly"/>
                                        </td>

                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td style="width: 3%">序号</td>
                                        <td colspan="3">物料描述</td>
                                        <td style="width: 8%">物料编码</td>
                                        <td style="width: 4%">预购单位</td>
                                        <td style="width: 6%">预购数量</td>
                                        <td style="width: 6%">业务员</td>
                                        <td style="width: 10%">预购备注</td>
                                        <td style="width: 6%">品牌</td>
                                        <td style="width: 8%">预购项目号</td>
                                        <td style="width: 12%">预购项目名</td>
                                        <td></td>
                                    </tr>
                                    </thead>
                                    <tbody id="out">
                                    <tr>
                                        <td>1</td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc"
                                                   autocomplete="off" maxlength="255"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark"
                                                   autocomplete="off" maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off"
                                                   maxlength="255"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i
                                                    class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i
                                                    class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件"
                                                  upload_control_name="upload_control_name1"><i
                                                    class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile"
                                                   style="display: none;"/>
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </form>
                    </div>
                    <!--                    <div th:include="include :: tip"></div>-->
                </section>
            </div>
        </div>
    </div>
</div>
<!--修改-->
<div class="modal fade" id="modal-update">
    <div class="modal-dialog" style="width:100%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">修改预购计划</h4>
            </div>
            <div class="modal-body">
                <section class="content" style="padding: 5px!important;">
                    <div class="row" style="margin-bottom: 24px">
                        <button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>
                        <a id="btn-update-report-plan" shiro:hasPermission="buy:preorderplan:edit"
                           href="javascript:void(0);"
                           class="btn btn-info pull-right" style="margin-right: 10px">
                            <span class="Bold">确定</span>
                        </a>
                        <a shiro:hasPermission="buy:preorderplan:edit" href="javascript:void(0);"
                           class="btn btn-success pull-right" style="margin-right: 10px"
                           onclick="js.modal.open('modal-import-plan')">
                            <span class="Bold">导入</span>
                        </a>
                    </div>
                    <div class="row">
                        <form id="updatePreOrderPlanForm" class="form-horizontal">
                            <div class="col-xs-12"
                                 style="max-width: 100%;max-height: 80vh;overflow: auto;padding: 0!important;">
                                <table id="table_import_update" class="t1 t3">
                                    <thead>
                                    <!--                                    <tr>-->
                                    <!--                                        <td colspan="12">-->
                                    <!--                                            <img th:src="@{/img/logo.png}" width="64px" height="40px"-->
                                    <!--                                                 style="margin-top: -30px">-->
                                    <!--                                            <div style="display: inline-block;margin-top: 5px;margin-left: 20px">-->
                                    <!--                                                <span style="letter-spacing: 24px;display: block;line-height: 20px">&nbsp;辽宁忠旺机械设备制造有限公司</span>-->
                                    <!--                                                <span style="display: block;font-size: 12px;line-height: 20px">Liaoning Zhongwang Machinery Equipment Manufacturing Co., Ltd</span>-->
                                    <!--                                            </div>-->
                                    <!--                                        </td>-->
                                    <!--                                        <td style="width: 8%"></td>-->
                                    <!--                                    </tr>-->
                                    <tr>
                                        <td colspan="12" style="font-size: 16px;letter-spacing: 4px;">
                                            预购计划单
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" style="width: 8%">主题</td>
                                        <td colspan="7" style="width: 11%;font-size: 14px;">
                                            <input type="text" class="form-control" name="name"
                                                   placeholder="请输入预购主题"/>
                                        </td>
                                        <td style="width: 8%">预购编号</td>
                                        <td colspan="2" style="width: 21%">
                                            <input style="background: #FFFFFF" type="text" class="form-control"
                                                   name="code" readonly="readonly"/>
                                        </td>

                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td style="width: 3%">序号</td>
                                        <td colspan="3">物料描述</td>
                                        <td style="width: 8%">物料编码</td>
                                        <td style="width: 4%">预购单位</td>
                                        <td style="width: 6%">预购数量</td>
                                        <td style="width: 6%">业务员</td>
                                        <td style="width: 10%">预购备注</td>
                                        <td style="width: 6%">品牌</td>
                                        <td style="width: 8%">预购项目号</td>
                                        <td style="width: 12%">预购项目名</td>
                                        <td></td>
                                    </tr>
                                    </thead>
                                    <tbody id="outForUpdate">
                                    <tr>
                                        <td>1</td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc1"
                                                   autocomplete="off" maxlength="255"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark"
                                                   autocomplete="off" maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off"
                                                   maxlength="255"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i
                                                    class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i
                                                    class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件"
                                                  upload_control_name="upload_control_name1"><i
                                                    class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile"
                                                   style="display: none;"/>
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                            <input type="hidden" class="form-control" name="id" readonly="readonly"/>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </form>
                    </div>
                    <!--                    <div th:include="include :: tip"></div>-->
                </section>
            </div>
        </div>
    </div>
</div>
<!--详情-->
<div class="modal fade" id="modal-info">
    <div class="modal-dialog" style="width:100%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">查看预购计划</h4>
            </div>
            <div class="modal-body">
                <section class="content" style="padding: 5px!important;">
                    <div class="row">
                        <form id="infoPreOrderPlanForm" class="form-horizontal">
                            <div class="col-xs-12"
                                 style="max-width: 100%;max-height: 80vh;overflow: auto;padding: 0!important;">
                                <table id="table_import_info" class="t1 t3">
                                    <thead>
                                    <!--                                    <tr>-->
                                    <!--                                        <td colspan="12">-->
                                    <!--                                            <img th:src="@{/img/logo.png}" width="64px" height="40px"-->
                                    <!--                                                 style="margin-top: -30px">-->
                                    <!--                                            <div style="display: inline-block;margin-top: 5px;margin-left: 20px">-->
                                    <!--                                                <span style="letter-spacing: 24px;display: block;line-height: 20px">&nbsp;辽宁忠旺机械设备制造有限公司</span>-->
                                    <!--                                                <span style="display: block;font-size: 12px;line-height: 20px">Liaoning Zhongwang Machinery Equipment Manufacturing Co., Ltd</span>-->
                                    <!--                                            </div>-->
                                    <!--                                        </td>-->
                                    <!--                                        <td style="width: 8%"></td>-->
                                    <!--                                    </tr>-->
                                    <tr>
                                        <td colspan="12" style="font-size: 16px;letter-spacing: 4px;">
                                            预购计划单
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" style="width: 8%">主题</td>
                                        <td colspan="7" style="width: 11%;font-size: 14px;">
                                            <input type="text" class="form-control" name="name"
                                                   placeholder="请输入预购主题"/>
                                        </td>
                                        <td style="width: 8%">预购编号</td>
                                        <td colspan="2" style="width: 21%">
                                            <input style="background: #FFFFFF" type="text" class="form-control"
                                                   name="code" readonly="readonly"/>
                                        </td>

                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td style="width: 3%">序号</td>
                                        <td colspan="3">物料描述</td>
                                        <td style="width: 8%">物料编码</td>
                                        <td style="width: 4%">预购单位</td>
                                        <td style="width: 6%">预购数量</td>
                                        <td style="width: 6%">业务员</td>
                                        <td style="width: 10%">预购备注</td>
                                        <td style="width: 6%">品牌</td>
                                        <td style="width: 8%">预购项目号</td>
                                        <td style="width: 12%">预购项目名</td>
                                        <td></td>
                                    </tr>
                                    </thead>
                                    <tbody id="outForInfo">
                                    <tr>
                                        <td>1</td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc"
                                                   autocomplete="off" maxlength="255"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark"
                                                   autocomplete="off" maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off"
                                                   maxlength="255"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off"
                                                   maxlength="255">
                                        </td>
                                        <td>
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                            <input type="hidden" class="form-control" name="id" readonly="readonly"/>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </form>
                    </div>
                    <!--                    <div th:include="include :: tip"></div>-->
                </section>
            </div>
        </div>
    </div>
</div>
<!--导入模态框-->
<div class="modal fade" data-backdrop="static" data-keyboard="false" id="modal-import-plan">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Excel信息导入</h4>
            </div>
            <div class="modal-body">
                <form id="importForm">
                    <div class="form-group">
                        <label>模版</label>
                        <a class="out" th:href="@{/file/预购导入模版.xlsx}">点击下载</a>
                    </div>
                    <div class="form-group">
                        <label>选择Excel文件并上传</label>
                        <input id="import-file" class="btn" type="file" name="file">
                        <p class="help-block">请按模板格式进行导入，信息与模板信息对应。</p>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="btn-import" type="button" class="btn btn-success">
                    <span class="Bold">确定</span>
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<!--指派-->
<div class="modal fade" id="modal-assign">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">指派采购员</h4>
            </div>
            <div class="modal-body">
                <form id="assignForm" class="form-horizontal">
                    <input type="hidden" name="sppId">
                    <input type="hidden" name="rppId">
                    <div class="row">
                        <div class="form-group">
                            <label for="assignPurchaserId" class="col-sm-4 control-label">采购员</label>
                            <div class="col-sm-8">
                                <input type="hidden" id="assignCode" name="code"/>
                                <select required id="assignPurchaserId" class="form-control select2"
                                        name="assignPurchaserId">

                                </select>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="btn-assign-reject">撤销</button>
                <button type="button" class="btn btn-info" id="btn-assign-save">保存指派</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<section class="content-header"><h1>预购计划编辑</h1></section>
<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-header">
                    <form id="queryForm" method="get">
                        <div class="row">
                            <div class="form-inline">
                                <div class="form-group">
                                    <label>预购主题</label>
                                    <input type="text" name="name" class="form-control"
                                           placeholder="请输入预购主题">
                                </div>
                                <div class="form-group">
                                    <label>预购编号</label>
                                    <input type="text" name="code" class="form-control"
                                           placeholder="请输入预购编号">
                                </div>
                                <div class="form-group">
                                    <label>申请人</label>
                                    <input type="text" name="applicant" class="form-control" placeholder="请输入申请人">
                                </div>
                                <div class="form-group">
                                    <label>指派业务员</label>
                                    <input type="text" name="assignPurchaser" class="form-control"
                                           placeholder="请输入指派业务员">
                                </div>
                                <div class="form-group">
                                    <label>审核状态</label>
                                    <select name="statusSelect"
                                            class="form-control selectpicker" data-actions-box="true" multiple
                                            style="padding: 0px!important;text-align: center!important;text-align-last: center!important;width:auto!important;">
                                        <option value="1" selected="selected">未提交</option>
                                        <option value="2">待科级审</option>
                                        <option value="3">待部级审</option>
                                        <option value="4">待指派</option>
                                        <option value="5">已指派</option>
                                    </select>
                                    <input type="hidden" name="statusStr" />
                                </div>
                                <div class="form-group">
                                    <label>预购日期</label>
                                    <input type="text" class="form-control datepicker" name="createTimeStartTime"
                                           readonly="readonly"/>
                                    <span> 至 </span>
                                    <input type="text" class="form-control datepicker" name="createTimeEndTime"
                                           readonly="readonly"/>
                                </div>
                                <button type="button" class="btn btn-success" id="btn-search">
                                    <span class="Bold">搜索</span>
                                </button>
                            </div>

                        </div>
                    </form>
                    <div class="row" id="toolbar">
                        <div class="form-inline">
                            <a shiro:hasPermission="buy:preorderdetails:view" th:href="@{/buy/preOrderDetails/page}"
                               class="btn btn-info pull-right" style="margin-right: 10px">
                                <span class="Bold">预购明细列表</span>
                            </a>
                            <a shiro:hasPermission="buy:preorderplan:delete" href="javascript:void(0);"
                               class="btn btn-danger pull-right" style="margin-right: 10px" onclick="deleteAll()">
                                <span class="Bold">批量删除</span>
                            </a>
                            <a shiro:hasPermission="buy:preorderplan:submit" href="javascript:void(0);"
                               class="btn btn-success pull-right" style="margin-right: 10px" onclick="submitAll()">
                                <span class="Bold">批量提交</span>
                            </a>
                            <a shiro:hasPermission="buy:preorderplan:add" href="javascript:void(0);"
                               class="btn btn-primary pull-right" style="margin-right: 10px"
                               onclick="openCreateModal()">
                                <span class="Bold">添加</span>
                            </a>
                        </div>
                    </div>
                </div>
                <div class="box-body">
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </div>
    </div>
</section>
<div th:include="include :: footer"></div>
<script th:inline="javascript">

    let table;
    let receiptStatusState = ['', "未收货", "部分收货", "无需收货", "收货完成"];
    let receiptStatusColors = ['', "label-info", "label-warning", "label-primary", "label-success"];
    let statusState = ['已删除', "未提交", "已提交", "被驳回", "已撤消", "待指派", "已指派"];
    let statusColors = ['label-danger', "label-default", "label-primary", "label-warning", "label-danger", "label-success", "label-primary"];
    let importTarget = '';

    /**
     * 批量删除
     */
    function deleteAll() {
        let selectedRows = table.bootstrapTable('getSelections');
        //提取选中行的唯一ID（假设ID字段为'code'）
        let selectedCodes = selectedRows.map(row => {
            //如果是 未提交 已驳回 已撤销的 可以进行删除
            if (row.status === 1 || row.status === 3 || row.status === 4) {
                return row.code;
            }
        });
        let newSelectedCodes = [];
        for (let i = 0; i < selectedCodes.length; i++) {
            if(selectedCodes[i] !== undefined){
                newSelectedCodes.push(selectedCodes[i]);
            }
        }
        if(newSelectedCodes.length === 0){
            js.modal.warning("所选预购计划所属状态无法删除");
            return;
        }
        selectedCodes = newSelectedCodes;
        let deleteCodesStr = "";
        for (let i = 0; i < selectedCodes.length; i++) {
            deleteCodesStr += "【" + selectedCodes[i] + "】,";
        }
        deleteCodesStr = deleteCodesStr.substring(0, deleteCodesStr.length - 1);
        js.modal.confirm("您确认要删除预购编号为：" + deleteCodesStr + "的预购计划吗？", function () {
            $.post(ctx + "buy/preOrderPlan/deleteByCodes", {
                codes: selectedCodes
            }, function (result) {
                if (result.type === "SUCCESS") {
                    search();
                }
            }, 'json');
        });
    }

    /**
     * 提交
     * @param code
     */
    function submitPreOrderPlan(code) {
        doSubmit([code]);
    }

    /**
     * 批量提交
     */
    function submitAll() {
        let selectedRows = table.bootstrapTable('getSelections');
        //提取选中行的唯一ID（假设ID字段为'code'）
        const selectedCodes = selectedRows.map(row => {
            //如果是 未提交 可以进行提交
            if (row.status === 1) {
                return row.code;
            }
        });
        doSubmit(selectedCodes);
    }

    /**
     * 执行提交
     * @param selectedCodes
     */
    function doSubmit(selectedCodes) {
        let deleteCodesStr = "";
        for (let i = 0; i < selectedCodes.length; i++) {
            deleteCodesStr += "【" + selectedCodes[i] + "】,";
        }
        deleteCodesStr = deleteCodesStr.substring(0, deleteCodesStr.length - 1);
        js.modal.confirm("您确认要提交预购编号为：" + deleteCodesStr + "的预购计划吗？", function () {
            $.post(ctx + "buy/preOrderPlan/submitByCodes", {
                codes: selectedCodes
            }, function (result) {
                if (result.type === "SUCCESS") {
                    js.modal.success(result.msg);
                    js.table.refresh(table);
                }
            }, 'json');
        });
    }

    /**
     * 搜索
     */
    function search() {
        js.table.refresh(table);
    }

    /** 计算表格序号 */
    function computerNo() {
        $("#table_import tbody tr").each(function (i, e) {
            let rowNum = eval(i + 1);
            $(this).children("td:first").text(rowNum);
        });
    }

    /** 计算表格序号 */
    function computerNoForUpdate() {
        $("#table_import_update tbody tr").each(function (i, e) {
            let rowNum = eval(i + 1);
            $(this).children("td:first").text(rowNum);
        });
    }

    /**
     * 删除预购计划
     * @param code
     */
    function deletePreOrderPlan(code) {
        js.modal.confirm("您确认要删除预购编号为：【" + code + "】的预购单吗？", function () {
            $.post(ctx + "buy/preOrderPlan/deleteByCodes", {
                codes: [code]
            }, function (result) {
                if (result.type == "SUCCESS") {
                    search();
                }
            }, 'json');
        });
    }

    /**
     * 下载附件
     * @param id 附件所属数据行ID
     * @param fileNameTitle 文件名
     */
    function downloadFile(id, fileNameTitle) {
        if (hasP('buy:preorderplan:download')) {
            if (fileNameTitle !== undefined && fileNameTitle !== null) {
                js.post({
                    url: ctx + "buy/preOrderPlan/getAttachmentIsExist",
                    data: {id: id},
                    success: function (result) {
                        //如果文件存在
                        if (result.msg == "有文件") {
                            //下载文件
                            location.href = ctx + "buy/preOrderPlan/downloadAttachment/" + id;
                        } else {
                            js.modal.warning("没有附件可以下载！");
                        }
                    }
                });
            }
        } else {
            js.modal.warning("你没有下载权限！");
        }
    }

    /**
     * 打开指派模态框
     * @param code
     */
    function assign(code) {
        js.post({
            url: ctx + "buy/preOrderPlan/getAssignPurchaserList",
            success: function (result) {
                $("#assignCode").val(code);
                let assignPurchaserIdSelect = $("#assignPurchaserId");
                assignPurchaserIdSelect.empty();
                assignPurchaserIdSelect.append('<option value="">  --请选择--  </option>');
                for (let i = 0; i < result.data.length; i++) {
                    let user = result.data[i];
                    assignPurchaserIdSelect.append('<option value="' + user.id + '">' + user.name + '</option>');
                }
                js.modal.open("modal-assign");
            }
        })
    }

    /**
     * 打开修改模态框
     * @param code
     */
    function openUpdateModal(code) {
        js.post({
            url: ctx + "buy/preOrderPlan/getProOrderPlanListByCode",
            data: {code: code},
            success: function (result) {
                importTarget = 'update';
                let list = result.data;
                $('#updatePreOrderPlanForm input[name="name"]').val(list[0].name);
                $('#updatePreOrderPlanForm input[name="code"]').val(list[0].code);
                $("#outForUpdate").empty();
                for (let i = 0; i < list.length; i++) {
                    let fileClass = 'label-default';
                    let fileStatus = '无附件';
                    let fileNameTitle = '';
                    if (list[i].attachmentName !== undefined && list[i].attachmentName !== null && list[i].attachmentName !== '') {
                        fileClass = 'label-success';
                        fileStatus = '有附件';
                        fileNameTitle = 'title = ' + list[i].attachmentName + '（点击下载）';
                    }
                    let materialDesc = list[i].materialDesc === undefined?'':list[i].materialDesc;
                    let proCode = list[i].proCode === undefined?'':list[i].proCode;
                    let proName = list[i].proName === undefined?'':list[i].proName;
                    let purchaser = list[i].purchaser === undefined?'':list[i].purchaser;
                    let num = list[i].num === undefined?'':list[i].num;
                    let unit = list[i].unit === undefined?'':list[i].unit;
                    let brand = list[i].brand === undefined?'':list[i].brand;
                    let materialCode = list[i].materialCode === undefined?'':list[i].materialCode;
                    let preOrderRemark = list[i].preOrderRemark === undefined?'':list[i].preOrderRemark;
                    $("#outForUpdate").append(`<tr>
                                        <td></td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" value="${materialDesc}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" value="${materialCode}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" value="${unit}" />
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01" value="${num}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" value="${purchaser}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" value="${preOrderRemark}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" value="${brand}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" value="${proCode}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" value="${proName}" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label onclick="downloadFile(${list[i].id},\'${fileNameTitle}\')" class="badge ${fileClass}" name="uploadFileText" ${fileNameTitle}>${fileStatus}</label>
                                            <input type="hidden" class="form-control" name="id" readonly="readonly" value="${list[i].id}" />
                                        </td>
                                    </tr>`);
                }
                computerNoForUpdate();
                js.modal.open("modal-update");
            }
        })

    }

    /**
     * 打开详情模态框
     * @param code
     */
    function openInfoModal(code) {
        js.post({
            url: ctx + "buy/preOrderPlan/getProOrderPlanListByCode",
            data: {code: code},
            success: function (result) {
                let list = result.data;
                $('#infoPreOrderPlanForm input[name="name"]').val(list[0].name);
                $('#infoPreOrderPlanForm input[name="code"]').val(list[0].code);
                $("#outForInfo").empty();
                for (let i = 0; i < list.length; i++) {
                    let fileClass = 'label-default';
                    let fileStatus = '无附件';
                    let fileNameTitle = '';
                    if (list[i].attachmentName !== undefined && list[i].attachmentName !== null && list[i].attachmentName !== '') {
                        fileClass = 'label-success';
                        fileStatus = '有附件';
                        fileNameTitle = 'title = ' + list[i].attachmentName + '（点击下载）';
                    }
                    let no = i + 1;
                    let materialDesc = list[i].materialDesc === undefined?'':list[i].materialDesc;
                    let proCode = list[i].proCode === undefined?'':list[i].proCode;
                    let proName = list[i].proName === undefined?'':list[i].proName;
                    let purchaser = list[i].purchaser === undefined?'':list[i].purchaser;
                    let num = list[i].num === undefined?'':list[i].num;
                    let unit = list[i].unit === undefined?'':list[i].unit;
                    let brand = list[i].brand === undefined?'':list[i].brand;
                    let materialCode = list[i].materialCode === undefined?'':list[i].materialCode;
                    let preOrderRemark = list[i].preOrderRemark === undefined?'':list[i].preOrderRemark;
                    $("#outForInfo").append(`<tr>
                                        <td>${no}</td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" style="background: #FFFFFF;" name="materialDesc" autocomplete="off" maxlength="255" value="${materialDesc}"  readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" style="background: #FFFFFF;"  name="materialCode" autocomplete="off" maxlength="255" value="${materialCode}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" style="background: #FFFFFF;"  name="unit" autocomplete="off" maxlength="255" value="${unit}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" style="background: #FFFFFF;"  name="num" min="0" step="0.01" value="${num}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" style="background: #FFFFFF;"  name="purchaser" autocomplete="off" maxlength="255" value="${purchaser}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" style="background: #FFFFFF;"  name="preOrderRemark" autocomplete="off" maxlength="255" value="${preOrderRemark}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" style="background: #FFFFFF;"  name="brand" autocomplete="off" maxlength="255" value="${brand}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" style="background: #FFFFFF;"  name="proCode" autocomplete="off" maxlength="255" value="${proCode}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" style="background: #FFFFFF;"  name="proName" autocomplete="off" maxlength="255" value="${proName}" readonly="readonly"/>
                                        </td>
                                        <td>
                                            <label onclick="downloadFile(${list[i].id},\'${fileNameTitle}\')" class="badge ${fileClass}" name="uploadFileText" ${fileNameTitle}>${fileStatus}</label>
                                            <input type="hidden" class="form-control" name="id" readonly="readonly" value="${list[i].id}" />
                                        </td>
                                    </tr>`);
                }
                js.modal.open("modal-info");
            }
        })

    }

    /** 添加模态框 */
    function openCreateModal() {
        js.post({
            url: ctx + "buy/preOrderPlan/getCode",
            data: {},
            success: function (result) {
                importTarget = 'create';
                $('#createPreOrderPlanForm input[name="code"]').val(result.data);
                $("#out").html(`<tr>
                                        <td>1</td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                        </td>
                                    </tr>`);
                js.modal.open("modal-create");
            }
        })
    }

    $(function (){
        $("#queryForm [name='statusSelect']").val([1,4]).selectpicker('refresh');
        $("#queryForm input[name='statusStr']").val($("#queryForm [name='statusSelect']").val());
        /**
         * 驳回
         */
        $("#btn-assign-reject").click(function (e){
            js.modal.confirm("确定撤销此预购计划吗?", function () {
               let selectedCode = $("#assignCode").val();
               let selectedCodes = [selectedCode];
                doReject(selectedCodes,'被驳回');
            });
        });
        /**
         * 执行驳回
         * @param codes 被驳回的预购单编号数组
         * @param reason 驳回原因
         */
        function doReject(codes,reason) {
            js.post({
                url: ctx + "buy/preOrderPlan/reject",
                data: {
                    codes: codes,
                    rejectReason: reason
                },
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {
                        location.reload();
                    } else {
                        js.modal.warning(result.msg);
                    }
                }
            })
        }
        /**
         * 保存指派结果并刷新列表
         */
        $("#btn-assign-save").click(function (e) {
            let assignPurchaserId = $('#assignPurchaserId').select2('val');
            if(assignPurchaserId === "")
            {
                js.modal.warning("请选择业务员！");
            }else{
                js.post({
                    url: ctx + "buy/preOrderPlan/assign",
                    data: {
                        code:$("#assignCode").val(),
                        assignPurchaserId:parseInt(assignPurchaserId),
                    },
                    success: function (result) {
                        if (result.type === 'SUCCESS'){
                            js.table.search(table);
                            js.modal.hide("modal-assign");
                            js.modal.success(result.msg)
                        }else {
                            js.modal.error(result.msg)
                        }
                    }
                });
            }
        });


        /** 修改删除行 */
        $('#updatePreOrderPlanForm').on('click', '.out-del', function () {
            $(this).parents("tr").remove();
            let trCount = $("#outForUpdate").find("tr").length;
            if (trCount === 0) {
                $("#outForUpdate").append(`<tr>
                                        <td></td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" />
                                        </td>
                                         <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" />
                                        </td>
                                         <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01" />
                                        </td>
                                        <td >
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label onclick="downloadFile(0,null)" class="badge label-default" name="uploadFileText" >无附件</label>
                                            <input type="hidden" class="form-control" name="id" readonly="readonly" value="0"/>
                                        </td>
                                    </tr>`)
            }
            computerNoForUpdate();
        });
        /** 修改添加一行 */
        $("#updatePreOrderPlanForm").on('click', '.out-add', function () {
            $(this).parents("tr").after(`<tr>
                                        <td></td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" autocomplete="off" />
                                        </td>
                                        <td >
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label onclick="downloadFile(0,null')" class="badge label-default" name="uploadFileText" >无附件</label>
                                            <input type="hidden" class="form-control" name="id" readonly="readonly" value="0"/>
                                        </td>
                                    </tr>`);
            computerNoForUpdate();
        });
        /** 删除行 */
        $('#createPreOrderPlanForm').on('click', '.out-del', function () {
            $(this).parents("tr").remove();
            let trCount = $("#out").find("tr").length;
            if (trCount === 0) {
                $("#out").append(`
                                <tr>
                                        <td></td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" />
                                        </td>
<td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01" />
                                        </td>
                                        <td >
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                        </td>
                                    </tr>
                            `)
            }
            computerNo();
        });
        /** 添加一行 */
        $("#createPreOrderPlanForm").on('click', '.out-add', function () {
            $(this).parents("tr").after(`
                    <tr>
                                        <td></td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" />
                                        </td>
                                         <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" />
                                        </td>
                                         <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                        </td>
                                    </tr>
            `);
            computerNo();
        });
        /**
         * 创建预购计划上传
         */
        $("#createPreOrderPlanForm").on('click', '.out-upload', function () {
            $(this).next().trigger('click');
        });
        /**
         * 修改预购计划上传
         */
        $("#updatePreOrderPlanForm").on('click', '.out-upload', function () {
            $(this).next().trigger('click');
        });
        /**
         * 创建预购计划 如果触发上传
         */
        $("#createPreOrderPlanForm").on('change', '.upload-file-c', function (e) {
            const file = e.target.files[0];
            if (!file) return;
            const sizeInBytes = file.size;    // 字节大小
            // 换算成 GB 保留两位小数
            const sizeInGB = (sizeInBytes / 1024 / 1024 / 1024).toFixed(2);
            // 如果文件大小大于2GB
            if (sizeInGB > 2) {
                js.modal.warning("文件大小不得大于2GB!");
                e.target.value = '';   // 清空已选文件
                return;
            }
            //如果上传成功
            if (e.target.files.length > 0) {
                $(this).next().text("有附件");
                $(this).next().attr("class", "badge label-success");
                $(this).next().attr("title", e.target.files[0].name);
            }
            //如果取消上传
            else {
                $(this).next().text("无附件");
                $(this).next().attr("class", "badge label-default");
                $(this).next().attr("title", "");
            }
        });
        /**
         * 提报状态改变事件
         */
        $("#queryForm [name='statusSelect']").on('change', function () {
            $("#queryForm input[name='statusStr']").val($("#queryForm [name='statusSelect']").val());
        });
        /**
         * 修改预购计划 如果触发上传
         */
        $("#updatePreOrderPlanForm").on('change', '.upload-file-c', function (e) {
            const file = e.target.files[0];
            if (!file) return;
            const sizeInBytes = file.size;    // 字节大小
            // 换算成 GB 保留两位小数
            const sizeInGB = (sizeInBytes / 1024 / 1024 / 1024).toFixed(2);
            // 如果文件大小大于2GB
            if (sizeInGB > 2) {
                js.modal.warning("文件大小不得大于2GB!");
                e.target.value = '';   // 清空已选文件
                return;
            }
            //如果上传成功
            if (e.target.files.length > 0) {
                $(this).next().text("有附件");
                $(this).next().attr("class", "badge label-success");
                $(this).next().attr("title", e.target.files[0].name);
            }
            //如果取消上传
            else {
                $(this).next().text("无附件");
                $(this).next().attr("class", "badge label-default");
                $(this).next().attr("title", "");
            }
        });
        /** 导入 */
        $('#btn-import').click(function () {
            let files = $("#import-file")[0].files;
            let fileReader = new FileReader();
            fileReader.onload = function (ev) {
                let workbook;
                let plans;
                try {
                    let data = ev.target.result,
                        workbook = XLSX.read(data, {type: 'binary'}), // 以二进制流方式读取得到整份excel表格对象
                        plans = []; // 存储获取到的数据
                    // 遍历每张表读取
                    for (let sheet in workbook.Sheets) {
                        if (workbook.Sheets.hasOwnProperty(sheet)) {
                            plans = plans.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                            break; // 只取第一张表
                        }
                    }
                    if (plans.length === 0) {
                        js.modal.alert("无法读取文件内容");
                    } else {
                        $("#out").empty();
                        plans.forEach((value, index) => {
                            let brand = value['品牌'] || '';
                            let materialCode = value['物料编码'] || '';
                            let preOrderRemark = value['预购备注'] || '';
                            let materialDesc  = value['物料描述'] || '';
                            materialDesc = materialDesc + '';
                            value['物料描述'] = materialDesc.replace(",", "，");
                            value['预购项目号'] = value['预购项目号'] || '';
                            value['预购项目名'] = value['预购项目名'] || '';
                            value['业务员'] = value['业务员'] || '';
                            value['预购数量'] = value['预购数量'] || '';
                            value['预购单位'] = value['预购单位'] || '';
                            if (importTarget === 'create') {
                                $("#out").append(`<tr>
                                        <td>1</td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" value="${value['物料描述']}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" value="${materialCode}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" value="${value['预购单位']}" />
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01" value="${value['预购数量']}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" value="${value['业务员']}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" value="${preOrderRemark}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" value="${brand}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" value="${value['预购项目号']}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" value="${value['预购项目名']}" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                        </td>
                                    </tr>`);
                            } else if (importTarget === 'update') {
                                $("#outForUpdate").append(`<tr>
                                        <td>1</td>
                                        <td colspan="3">
                                            <input type="text" class="form-control" name="materialDesc" autocomplete="off" maxlength="255" value="${value['物料描述']}" />
                                        </td>
                                            <td>
                                            <input type="text" class="form-control" name="materialCode" autocomplete="off" maxlength="255" value="${materialCode}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="unit" autocomplete="off" maxlength="255" value="${value['预购单位']}" />
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" name="num" min="0" step="0.01" value="${value['预购数量']}" />
                                        </td>
                                        <td >
                                            <input type="text" class="form-control" name="purchaser" autocomplete="off" maxlength="255" value="${value['业务员']}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="preOrderRemark" autocomplete="off" maxlength="255" value="${preOrderRemark}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="brand" autocomplete="off" maxlength="255" value="${brand}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proCode" autocomplete="off" maxlength="255" value="${value['预购项目号']}" />
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" name="proName" autocomplete="off" maxlength="255" value="${value['预购项目名']}" />
                                        </td>
                                        <td>
                                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
                                            <span class="out-upload" title="上传附件" upload_control_name="upload_control_name"><i class="fa fa-upload text-success"></i> </span>
                                            <input class="upload-file-c" type="file" name="uploadFile" style="display: none;" />
                                            <label class="badge label-default" name="uploadFileText">无附件</label>
                                            <input type="hidden" class="form-control" name="id" readonly="readonly" value="0"/>
                                        </td>
                                    </tr>`);
                            }

                        });
                        if (importTarget === 'create') {
                            computerNo();
                        } else if (importTarget === 'update') {
                            computerNoForUpdate();
                        }

                        js.modal.hide("modal-import-plan");
                    }
                } catch (e) {
                    js.modal.alert("无法读取文件或文件类型有错误");
                }
            };
            // 以二进制方式打开文件
            fileReader.readAsBinaryString(files[0]);
        });

        /** 预购计划表 */
        table = js.table.init({
            url: ctx + "buy/preOrderPlan/list",
            paginationVAlign: 'both',
            pageSize: 15,
            pageList: [10, 15, 25, 50, 100, 300, 1000],               // 可供选择的每页的行数
            showColumns: true,
            showExport: false,
            showRefresh: true,
            clickToSelect: true,
            // exportDataType: 'basic',
            // exportTypes: ['csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],
            // exportOptions: {
            //     ignoreColumn: [0, 19],  //忽略某一列的索引
            //     fileName: '提报计划列表',  //文件名称设置
            //     worksheetName: '提报计划列表',  //表格工作区名称
            //     tableName: '提报计划列表',
            // },
            uniqueId: "code",
            onLoadSuccess: function (){
                $('#btn-search').prop('disabled', false).removeClass('disabled');
            },
            columns: [
                {
                    checkbox: true,
                    width: '30px',
                    formatter: function (value, row, index) {
                        if (sessionUser.name == row.applicant || '管理员' == sessionUser.name) {
                            return {disabled: false}
                        } else {
                            return {disabled: true}
                        }
                    }
                },
                {
                    title: '序号', width: '50px',
                    formatter: function (value, row, index, field) {
                        return index + 1;
                    }
                },
                {
                    title: "预购主题", field: 'name',
                    formatter: function (value, row, index, field) {
                        if (value && value.length > 50) {
                            return '<span title="' + value + '">' + value.substring(0, 50) + '</span> ';
                        } else {
                            return value;
                        }
                    }
                },
                {
                    title: "预购编号", field: 'code', width: '170px'
                },
                {
                    title: "预购日期", field: 'createTime', width: '150px'
                },
                {
                    title: "审批状态", field: 'status', width: '100px',
                    formatter: function (value, row, index) {
                        if (value) {
                            return '<span class="badge ' + statusColors[value] + '">' + statusState[value] + '</span> ';
                        }
                    }
                },
                {title: "申请人", field: 'applicant', width: '100px'},
                {title: "指派业务员", field: 'assignPurchaser', width: '160px'},
                {title: "驳回原因", field: 'rejectReason', width: '100px'},
                {
                    title: "操作",
                    width: '240px',
                    formatter: function (value, row, index) {
                        var actions = [];
                        if (hasP('buy:preorderplan:view')) {
                            actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="openInfoModal(\'' + row.code + '\')"> 详情</a> ');
                        }
                        if (hasP('buy:preorderplan:edit') && (row.status === 1 || row.status === 3)) {
                            actions.push('<a class="btn btn-warning btn-xs" href="javascript:void(0)" onclick="openUpdateModal(\'' + row.code + '\')"> 修改</a> ');
                        }
                        if (hasP('buy:preorderplan:submit') && row.status === 1 || row.status === 3) {
                            actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="submitPreOrderPlan(\'' + row.code + '\')"> 提交</a> ');
                        }
                        if (hasP('buy:preorderplan:delete') && (row.status === 1 || row.status === 3)) {
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="deletePreOrderPlan(\'' + row.code + '\')"> 删除</a> ');
                        }
                        if (hasP('buy:preorderplan:assign') && row.status === 5) {
                            actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="assign(\'' + row.code + '\')"> 指派</a> ');
                        }
                        return actions.join('');
                    }
                }
            ]
        });


        /** 表格搜索 */
        $("#btn-search").click(function () {
            $('#btn-search').prop('disabled', true).addClass('disabled');
            js.table.search(table);
        });


        /** 添加模态框隐藏事件 */
        js.modal.hideEvent("modal-create", function () {
            $("#btn-create-report-plan").removeAttr("disabled");
            js.reset("createPreOrderPlanForm");
        });

        /** 修改模态框隐藏事件 */
        js.modal.hideEvent("modal-update", function () {
            $("#btn-update-report-plan").removeAttr("disabled");
            js.reset("updatePreOrderPlanForm");
        });

        /** 导入表单验证 */
        js.validate.init("importForm", {
            fields: {
                file: {
                    validators: {
                        notEmpty: {message: '上传文件不能为空'},
                        file: {extension: 'xls,xlsx', message: '请选择excel文件'}
                    }
                }
            }
        });
        /** 导入模态框隐藏事件 */
        js.modal.hideEvent("modal-import", function () {
            js.validate.reset("importForm");
            js.reset("importForm");
        });


        /**
         * 表格多行数据中必填项验证
         * @param tbodyId tbodyId
         * @param nameArray 必填项名称数组
         * return 验证是否通过
         */
        function requiredFieldVerification(tbodyId, nameArray) {
            let isPass = true;
            let tBody = $('#' + tbodyId);
            let trCount = tBody.children('tr').length;
            let passCount = 0;
            if (trCount > 0) {
                let trs = tBody.children("tr");
                let firstPurchaser = $(trs[0]).find("input[name='purchaser']").val();
                for (let i = 0; i < trCount; i++) {
                    for (let j = 0; j < nameArray.length; j++) {
                        let input_element = $(trs[i]).find("input[name='" + nameArray[j] + "']");
                        if (input_element.val() === "") {
                            input_element.css({
                                'border-color': 'red',
                                'border-style': 'solid',
                                'border-width': '1px'
                            });
                            createTipBox(input_element, "必填！", input_element.parent());
                            isPass = false;
                        } else {
                            input_element.css({
                                'border-color': 'transparent',
                                'border-style': 'none',
                                'border-width': '0px'
                            });
                            removeTipBox(input_element);
                        }
                    }
                }
                if (isPass) {
                    for (let i = 0; i < trCount; i++) {
                        for (let j = 0; j < nameArray.length; j++) {
                            let input_element = $(trs[i]).find("input[name='" + nameArray[j] + "']");
                            //如果是项目号
                            if (nameArray[j] === "proCode" && isPass === true) {
                                //验证是否存在
                                $.ajax({
                                    url: ctx + 'purchase/change/codeExist', // 请求路径
                                    type: 'POST',
                                    async: false,	// 同步请求，必须是false
                                    data: {
                                        ceoNeedProCode: input_element.val() // 请求参数
                                    },
                                    success: function (res) {
                                        let flag = $.parseJSON(res).valid;
                                        //如果验证未通过
                                        if (!flag) {
                                            input_element.css({
                                                'border-color': 'red',
                                                'border-style': 'solid',
                                                'border-width': '1px'
                                            });
                                            createTipBox(input_element, "项目号不存在！", input_element.parent());
                                            isPass = false;
                                        }
                                        //如果验证通过
                                        else {
                                            input_element.css({
                                                'border-color': 'transparent',
                                                'border-style': 'none',
                                                'border-width': '0px'
                                            });
                                            removeTipBox(input_element);
                                            passCount++;
                                        }
                                    }
                                });
                            }
                        }
                    }
                    isPass = passCount === trCount;
                }
                // if (isPass) {
                //     for (let i = 0; i < trCount; i++) {
                //         for (let j = 0; j < nameArray.length; j++) {
                //             let input_element = $(trs[i]).find("input[name='" + nameArray[j] + "']");
                //             if (nameArray[j] === "purchaser" && isPass === true) {
                //                 if ($(tBody.children("tr")[i]).find("input[name='" + nameArray[j] + "']").val() === firstPurchaser) {
                //                     input_element.css({
                //                         'border-color': 'transparent',
                //                         'border-style': 'none',
                //                         'border-width': '0px'
                //                     });
                //                     removeTipBox(input_element);
                //                 } else {
                //                     input_element.css({
                //                         'border-color': 'red',
                //                         'border-style': 'solid',
                //                         'border-width': '1px'
                //                     });
                //                     createTipBox(input_element, "此列必须相符", input_element.parent());
                //                     isPass = false;
                //                 }
                //             }
                //         }
                //     }
                // }

            } else {
                isPass = false;
            }
            return isPass;
        }

        /** 创建-导入提报计划 */
        $("#btn-create-report-plan").click(function () {
            $("#btn-create-report-plan").attr("disabled", "disabled");
            let isPass = true;
            let input_name = $("#createPreOrderPlanForm input[name='name']");
            let nameVal = input_name.val();
            let codeVal = $("#createPreOrderPlanForm input[name='code']").val();
            if (nameVal === "") {
                input_name.css({
                    'border-color': 'red',
                    'border-style': 'solid',
                    'border-width': '1px'
                });
                createTipBox(input_name, "预购主题不可为空！", input_name.parent());
                isPass = false;
                $("#btn-create-report-plan").removeAttr("disabled");
            } else {
                input_name.css({
                    'border-color': 'transparent',
                    'border-style': 'none',
                    'border-width': '0px'
                });
                removeTipBox(input_name);
            }
            if (isPass) {
                // let nameArray = ["materialDesc", "proCode", "proName", "purchaser", "num", "unit"];
                let nameArray = ["materialDesc", "proCode", "proName", "num", "unit"];
                if (requiredFieldVerification("out", nameArray)) {
                    // 1. 创建 FormData 存储所有数据和文件
                    let formData = new FormData();
                    formData.append('name', nameVal);
                    formData.append('code', codeVal);
                    // 2. 遍历表格的每一行（tr）
                    $('#out tr').each(function (rowIndex) {
                        let $tr = $(this); // 当前行
                        let $td = $tr.find("td");
                        formData.append(`rows[${rowIndex}].materialDesc`, $td[1].children[0].value);
                        formData.append(`rows[${rowIndex}].materialCode`, $td[2].children[0].value);
                        formData.append(`rows[${rowIndex}].unit`, $td[3].children[0].value);
                        formData.append(`rows[${rowIndex}].num`, $td[4].children[0].value);
                        formData.append(`rows[${rowIndex}].purchaser`, $td[5].children[0].value);
                        formData.append(`rows[${rowIndex}].preOrderRemark`, $td[6].children[0].value);
                        formData.append(`rows[${rowIndex}].brand`, $td[7].children[0].value);
                        formData.append(`rows[${rowIndex}].proCode`, $td[8].children[0].value);
                        formData.append(`rows[${rowIndex}].proName`, $td[9].children[0].value);
                        let file = $td[10].children[3].files[0];
                        if (file) {
                            formData.append(`rows[${rowIndex}].uploadFile`, file);
                        }
                    });
                    //提交所有数据以及要上传的文件
                    $.ajax({
                        url: ctx + "buy/preOrderPlan/importExcel", // 后端接口地址
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (response) {
                            if (response.type === 'SUCCESS') {
                                js.modal.success(response.msg);
                                $("#btn-create-report-plan").removeAttr("disabled");
                                js.modal.hide("modal-create");
                                search();
                            } else {
                                js.modal.fail(response.msg);
                                $("#btn-create-report-plan").removeAttr("disabled");
                            }
                        },
                        error: function (xhr, status, error) {
                            $("#btn-create-report-plan").removeAttr("disabled");
                        }
                    });
                } else {
                    $("#btn-create-report-plan").removeAttr("disabled");
                }
            }
        });
        /** 修改-导入提报计划 */
        $("#btn-update-report-plan").click(function () {
            $("#btn-update-report-plan").attr("disabled", "disabled");
            let isPass = true;
            let input_name = $("#updatePreOrderPlanForm input[name='name']");
            let nameVal = input_name.val();
            let codeVal = $("#updatePreOrderPlanForm input[name='code']").val();
            if (nameVal === "") {
                input_name.css({
                    'border-color': 'red',
                    'border-style': 'solid',
                    'border-width': '1px'
                });
                createTipBox(input_name, "预购主题不可为空！", input_name.parent());
                isPass = false;
                $("#btn-update-report-plan").removeAttr("disabled");
            } else {
                input_name.css({
                    'border-color': 'transparent',
                    'border-style': 'none',
                    'border-width': '0px'
                });
                removeTipBox(input_name);
            }
            if (isPass) {
                // let nameArray = ["materialDesc", "proCode", "proName", "purchaser", "num", "unit"];
                let nameArray = ["materialDesc", "proCode", "proName", "num", "unit"];
                if (requiredFieldVerification("outForUpdate", nameArray)) {
                    // 1. 创建 FormData 存储所有数据和文件
                    let formData = new FormData();
                    formData.append('name', nameVal);
                    formData.append('code', codeVal);
                    // 2. 遍历表格的每一行（tr）
                    $('#outForUpdate tr').each(function (rowIndex) {
                        let $tr = $(this); // 当前行
                        let $td = $tr.find("td");
                        formData.append(`rows[${rowIndex}].materialDesc`, $td[1].children[0].value);
                        formData.append(`rows[${rowIndex}].materialCode`, $td[2].children[0].value);
                        formData.append(`rows[${rowIndex}].unit`, $td[3].children[0].value);
                        formData.append(`rows[${rowIndex}].num`, $td[4].children[0].value);
                        formData.append(`rows[${rowIndex}].purchaser`, $td[5].children[0].value);
                        formData.append(`rows[${rowIndex}].preOrderRemark`, $td[6].children[0].value);
                        formData.append(`rows[${rowIndex}].brand`, $td[7].children[0].value);
                        formData.append(`rows[${rowIndex}].proCode`, $td[8].children[0].value);
                        formData.append(`rows[${rowIndex}].proName`, $td[9].children[0].value);
                        formData.append(`rows[${rowIndex}].id`, $td[10].children[5].value);
                        let file = $td[10].children[3].files[0];
                        if (file) {
                            formData.append(`rows[${rowIndex}].uploadFile`, file);
                        }
                    });
                    //提交所有数据以及要上传的文件
                    $.ajax({
                        url: ctx + "buy/preOrderPlan/importExcelForUpdate", // 后端接口地址
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (response) {
                            if (response.type === 'SUCCESS') {
                                js.modal.success(response.msg);
                                $("#btn-update-report-plan").removeAttr("disabled");
                                js.modal.hide("modal-update");
                                search();
                            } else {
                                $("#btn-update-report-plan").removeAttr("disabled");
                                js.modal.fail(response.msg);
                            }
                        },
                        error: function (xhr, status, error) {
                            $("#btn-update-report-plan").removeAttr("disabled");
                        }
                    });
                } else {
                    $("#btn-update-report-plan").removeAttr("disabled");
                }
            } else {
                $("#btn-update-report-plan").removeAttr("disabled");
            }
        });

    });

    /**
     * 删除提示框
     * @param $targetInput
     */
    function removeTipBox($targetInput) {
        $("." + $targetInput.attr("name") + "custom-tip-box").remove();
    }

    /**
     * 创建提示框
     * @param $targetInput 目标Input
     * @param customTipText 提示内容
     * @param $parent 父级td
     */
    function createTipBox($targetInput, customTipText, $parent) {
        $parent.css({
            position: 'relative', // 核心：作为绝对定位的基准
            padding: '5px' // 可选：给父容器留一点内边距，避免提示框贴边
        });
        // 创建提示框容器
        var $tipBox = $('<div class="' + $targetInput.attr("name") + 'custom-tip-box"></div>').css({
            'position': 'absolute', // 改为相对定位
            'top': '0px', // 相对于父容器原始位置向下偏移5px（即input下方）
            'left': '0', // 相对于父容器左侧对齐
            'background': 'red',
            'color': 'white',
            'border-radius': '3px',
            'z-index': '10', // 无需过高，父容器内层级足够
            'display': 'flex',
            'align-items': 'center',
        });

        // 提示文字
        var $tipText = $('<span></span>').text(customTipText);

        // 关闭按钮
        var $closeBtn = $('<span>×</span>').css({
            'cursor': 'pointer',
            'font-weight': 'bold',
            'font-size': '14px',
            'user-select': 'none'
        });

        // 关闭按钮事件
        $closeBtn.on('click', function () {
            $tipBox.remove();
        });

        // 组装提示框
        $tipBox.append($tipText).append($closeBtn);
        $parent.append($tipBox);
    }
</script>
</body>
</html>